package com.zhss.eshop.auth.controller;

import com.zhss.eshop.auth.domain.model.AuthRole;
import com.zhss.eshop.auth.domain.model.AuthRolePriorityRelationship;
import com.zhss.eshop.auth.service.AuthRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色管理模块controller组件
 * @author suyuan
 * // TODO: 2021/3/5  角色关联账号、权限未做
 *
 */
@RestController
@RequestMapping("/auth/role")
public class RoleController {

	private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

	/**
	 * 角色管理模块service组件
	 */
	@Autowired
	private AuthRoleService roleService;

	/**
	 * 分页查询角色
	 * @return 角色VO集合
	 */
	@GetMapping("/")
	public List<AuthRole> listByPage(Integer page,Integer limit,String code,String name) {
		try {
			List<AuthRole> roles = roleService.listByPage(page,limit,code,name);
			return roles;
		} catch (Exception e) {
			logger.error("error", e);
			return new ArrayList<AuthRole>();
		}
	}

	/**
	 * 根据id查询角色
	 * @param id 角色id
	 * @return 角色
	 */
	@GetMapping("/{id}")
	public AuthRole getById(@PathVariable("id") Long id) {
		try {
			AuthRole role = roleService.selectByPrimaryKey(id);
			List<AuthRolePriorityRelationship> relations = role.getRolePriorityRelations();

			role.setRolePriorityRelations(relations);

			return role;
		} catch (Exception e) {
			logger.error("error", e);
			return new AuthRole();
		}
	}

	/**
	 * 新增角色
	 * @param role 角色
	 * @return 处理结果
	 */
	@PostMapping("/")
	public Boolean save(@RequestBody AuthRole role) {
		try {
			roleService.insertSelective(role);

			return true;
		} catch (Exception e) {
			logger.error("error", e);
			return false;
		}
	}

	/**
	 * 更新角色
	 * @param role 角色
	 * @return 处理结果
	 */
	@PutMapping("/{id}")
	public Boolean update(@RequestBody AuthRole role) {
		try {
			roleService.updateByPrimaryKeySelective(role);

			return true;
		} catch (Exception e) {
			logger.error("error", e);
			return false;
		}
	}

	/**
	 * 删除角色
	 * @param id 角色id
	 * @return 角色
	 */
	@DeleteMapping("/{id}")
	public Boolean remove(@PathVariable("id") Long id) {
		try {
			 roleService.deleteByPrimaryKey(id);
			return true;
		} catch (Exception e) {
			logger.error("error", e);
			return false;
		}
	}

}
